package name.fowler.refactoring.simplestore.web;

import name.fowler.refactoring.simplestore.domain.Customer;
import name.fowler.refactoring.simplestore.services.ReportBuilder;
import name.fowler.refactoring.simplestore.services.ReportBuilderFactory;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

public class ReportHandler implements Serializable {
    @Inject
    ReportBuilderFactory reportBuilderFactory;

    public ReportHandler() {
    }

    void buildReport(EntityManager entityManager, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Map<String, String[]> params) throws ServletException, IOException {
        httpServletRequest.setAttribute("title", "Oтчет");
        String repType = params.get("repType")[0];
        String formatType = params.get("formatType")[0];
        ReportBuilder reportBuilder = reportBuilderFactory.create(repType, formatType);
        List<Customer> customers = entityManager.createNamedQuery("customer.list", Customer.class).getResultList();
        httpServletRequest.setAttribute("report", reportBuilder.getReport(customers));
        httpServletRequest.getServletContext().getRequestDispatcher("/WEB-INF/report/report.jsp")
                .forward(httpServletRequest, httpServletResponse);
    }

    void chooseReport(EntityManager entityManager, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {
        httpServletRequest.setAttribute("title", "Выбор отчета");
        httpServletRequest.getServletContext().getRequestDispatcher("/WEB-INF/report/choose.jsp")
                .forward(httpServletRequest, httpServletResponse);
    }
}